package com.yanwq.sayhi.controller.club.fragment;


import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.pulltorefreshview.view.PullToLoadListener;
import com.yanwq.pulltorefreshview.view.PullToRefreshLayout;
import com.yanwq.pulltorefreshview.view.PullToRefreshListener;
import com.yanwq.pulltorefreshview.view.PullToRefreshRecyclerView;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseFragment;
import com.yanwq.sayhi.common.client.OkJsonArrayResponseCallback;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.event.ClubEvent;
import com.yanwq.sayhi.controller.club.activity.ClubAddActivity;
import com.yanwq.sayhi.controller.club.activity.ClubListActivity;
import com.yanwq.sayhi.controller.club.adapter.MyClubAdapter;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.ClubVip;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * A simple {@link Fragment} subclass.
 */
public class ClubListFragment extends BaseFragment {
    @BindView(R.id.cl_actionbar)
    View mVActionbar;
    @BindView(R.id.club_empty)
    View mVEmpty;
    @BindView(R.id.club_refresh)
    PullToRefreshLayout mSRLRefresh;
    @BindView(R.id.club_list)
    PullToRefreshRecyclerView mRecyclerView;

    @OnClick(R.id.cl_add_club)
    void addClub() {
        Intent intent = new Intent(getActivity(), ClubAddActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.cl_all_club)
    void allClub() {
        Intent intent = new Intent(getActivity(), ClubListActivity.class);
        startActivity(intent);
    }

    private MyClubAdapter mAdapter;
    private int mPage;
    private int mSize;
    private boolean mRefreshed;
    private long mRefreshTime;

    public ClubListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        EventBus.getDefault().register(this);
        return inflater.inflate(R.layout.fragment_club_list, container, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @SuppressWarnings("all")
    public void onEvent(ClubEvent event) {
        switch (event.getEventType()) {
            case ClubEvent.CREATED:
            case ClubEvent.EXITED:
            case ClubEvent.CHANGED:
                autoRefresh();
                break;
        }
    }

    private void autoRefresh() {
        post(new Runnable() {
            @Override
            public void run() {
                mSRLRefresh.startRefresh();
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && !mRefreshed) {
            mRefreshed = true;
            autoRefresh();
        }
    }

    @Override
    public void init() {
        mPage = 0;
        mSize = 20;
        mRefreshTime = System.currentTimeMillis();
        mAdapter = new MyClubAdapter(this);
    }

    @Override
    public void initView() {
        mVEmpty.setVisibility(View.GONE);

        mSRLRefresh.setPullToRefreshListener(new PullToRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        mSRLRefresh.setPullToLoadListener(new PullToLoadListener() {
            @Override
            public void onLoad() {
                load();
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        mRecyclerView.setHasFixedSize(true);
        View header = LayoutInflater.from(getActivity()).inflate(R.layout.head_article_list, mRecyclerView, false);
        mAdapter.addHeader(header);
        mRecyclerView.setAdapter(mAdapter);

        post(new Runnable() {
            @Override
            public void run() {
                /*mVStatusBarShadow.getLayoutParams().height = ((BaseActivity) getActivity()).getStatusBarHeight();
                mVStatusBarShadow.requestLayout();*/

                mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    int actionbarHeight = mVActionbar.getMeasuredHeight();
                    int currentHeight = actionbarHeight;

                    @Override
                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);
                        currentHeight -= dy;

                        if (currentHeight < 0) {
                            currentHeight = 0;
                        } else if (currentHeight > actionbarHeight) {
                            currentHeight = actionbarHeight;
                        }

                        float alpha = (float) currentHeight / actionbarHeight;
                        mVActionbar.setAlpha(alpha);
                    }
                });
            }
        });
    }

    private void refreshCount() {
        OkRequestParams params = new OkRequestParams();
        params.put("refreshTime", mRefreshTime);
        OkRestClient.getInstance().get(getActivity(), "/article/count", params, new OkJsonObjectResponseCallback() {
            @Override
            public void onSuccess(JSONObject jsonObject) {

            }

            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }
        });
    }

    private void refresh() {
        mPage = 0;
        OkRequestParams params = new OkRequestParams();
        params.put("userId", UserMgr.get().getId());
        params.put("page", mPage);
        params.put("size", mSize);
        OkRestClient.getInstance().get(getActivity(), "/clubVip/list/user", params, new OkJsonArrayResponseCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(JSONArray jsonArray) {
                List<ClubVip> clubs = JSON.parseArray(jsonArray.toJSONString(), ClubVip.class);
                mAdapter.refresh(clubs);

                if (clubs.size() > 0) {
                    mVEmpty.setVisibility(View.GONE);
                } else {
                    mVEmpty.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onStop() {
                mSRLRefresh.stopRefresh();
            }
        });
    }

    private void load() {
        mPage++;
        OkRequestParams params = new OkRequestParams();
        params.put("userId", UserMgr.get().getId());
        params.put("page", mPage);
        params.put("size", mSize);
        OkRestClient.getInstance().get(getActivity(), "/clubVip/list/user", params, new OkJsonArrayResponseCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(JSONArray jsonArray) {
                List<ClubVip> clubs = JSON.parseArray(jsonArray.toJSONString(), ClubVip.class);
                mAdapter.load(clubs);
            }

            @Override
            public void onStop() {
                mSRLRefresh.stopLoad();
            }
        });
    }
}
